package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var value int
var rwMutex sync.RWMutex

func main() {
	//播种随机数种子
	rand.Seed(time.Now().UnixNano())
	//创建5个写go程
	for i := 0; i < 5; i++ {
		go write(i + 1)
	}
	//创建5个读go程
	for i := 0; i < 5; i++ {
		go read(i + 1)
	}
	for {
	}
}

func read(idx int) {
	for {
		rwMutex.RLock() //读上锁
		num := value
		fmt.Printf("================第%d 个读go程，读入：%d\n", idx, num)
		rwMutex.RUnlock() //读解锁
		time.Sleep(time.Second)
	}
}

func write(idx int) {
	for {
		//生成随机数
		num := rand.Intn(1000)
		rwMutex.Lock() //写上锁
		value = num
		fmt.Printf("第%d 个写go程，写入：%d\n", idx, value)
		rwMutex.Unlock() //写解锁
		time.Sleep(2 * time.Second)
	}
}
